package com.valco.datacontrol.openapi;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.valco.data.Book;

public class OpenAPIXMLParserNaver implements OpenAPIXMLParser {

	private String getContent(Element element, String tagName) {
		NodeList list = element.getElementsByTagName(tagName);
		Element cElement = (Element) list.item(0);

		if (cElement.getFirstChild() != null) {
			return delTokenInValue(cElement.getFirstChild().getNodeValue());
		} else {
			return "";
		}
	}

	private String delTokenInValue(String strVal) {
		if (strVal == null || strVal == "")
			return strVal;
		strVal = strVal.replace("<b>", "");
		strVal = strVal.replace("</b>", "");
		return strVal;
	}

	@Override
	public ArrayList<Book> parseToData(RequestQueryData queryData, String uri) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		ArrayList<Book> listItem = new ArrayList<Book>();

		try {
			DocumentBuilder builder = dbf.newDocumentBuilder();
			Document doc = builder.parse(uri);
			Element root = doc.getDocumentElement();
			NodeList list = root.getElementsByTagName("item");

			for (int i = 0; i < list.getLength(); i++) {
				Element element = (Element) list.item(i);
				Book book = new Book();

				book.setAuthor(getContent(element, "author"));
				book.setDescription(getContent(element, "description"));
				book.setDiscount(Integer.parseInt(getContent(element, "discount")));
				book.setImage_url(getContent(element, "image"));
				book.setIsbn(getContent(element, "isbn"));
				
				String []isbn = getContent(element, "isbn").split(" ");
				book.setIsbn(isbn[0]);
				if (isbn.length>1) book.setIsbn13(isbn[1]);
				else book.setIsbn13(isbn[0]);
				
				book.setLink_url(getContent(element, "link"));
				book.setPrice(Integer.parseInt(getContent(element, "price")));
				book.setPubdate(getContent(element, "pubdate"));
				book.setPublisher(getContent(element, "publisher"));
				book.setTitle(getContent(element, "title"));

				element.getNodeName();

				listItem.add(book);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return listItem;
	}
}




